package top.lingkang.finalgateway.admin.config;

import cn.hutool.core.io.IoUtil;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.FilterChain;
import top.lingkang.finalgateway.admin.controller.WebController;
import top.lingkang.finalgateway.admin.dto.ResponseResult;
import top.lingkang.finalsecurity.common.base.FinalHttpProperties;
import top.lingkang.finalsecurity.common.error.FinalNotLoginException;
import top.lingkang.finalsecurity.solonplugin.config.FinalSecurityConfiguration;
import top.lingkang.finalvalidated.error.ValidatedException;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lingkang
 * Created by 2024/4/27
 */
@Component
@Slf4j
public class GlobalFilter extends FinalSecurityConfiguration {
    public static final String isLogin = "isLogin";
    private List<String> ex = new ArrayList<>();
    private String json404 = new ResponseResult<>().fail("404 final-gateway").toString();

    @Inject
    private WebController webController;

    public GlobalFilter() {
        ex.add("/res/**");
        ex.add("/api/user/login");
        ex.add("/api/user/logout");
        ex.add("/login");
    }

    @Override
    protected void config(FinalHttpProperties properties) {
        properties.checkAuthorize()
                .pathMatchers("/api/**").hasLogin();// 需要登录才能访问

        // 排除鉴权路径匹配, 匹配优先级别：排除路径 > checkAuthorize > 注解
        properties.setExcludePath(ex.toArray(new String[0]));

        /*properties.setExceptionHandler(new DefaultFinalExceptionHandler(){
            @Override
            public void notLoginException(Throwable e, Context request, Context response) {
                response.redirect("/login");
            }
        });*/
    }

    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        try {
            super.doFilter(ctx, chain);
            if (!ctx.getHandled()) {
                ctx.contentType("text/html;charset=utf-8");
                ctx.output((String) webController.index(ctx));
            }
        } catch (FinalNotLoginException e) {
            // 登录页面
            ctx.outputAsHtml(IoUtil.readUtf8(getClass().getClassLoader().getResourceAsStream("templates/login.ftl")));
        } catch (Throwable e) {
            if (e instanceof ValidatedException || e instanceof IllegalArgumentException) {
                ctx.outputAsJson(new ResponseResult<>().fail(e.getMessage()).toString());
                return;
            }
            e.printStackTrace();
            ctx.outputAsJson(new ResponseResult<>().fail("服务错误").toString());
        }
    }
}
